<?php 
/**
 * 车辆管理类
 * @Author    紫梦
 * @DateTime  2017-11-03
 * @copyright 响响租车
 * @version   1.0
 * @UpdateTime 2017-11-10
 */
namespace app\index\controller;
use \think\Request;
use \think\Db;
use app\common\model\Agency;
use app\common\model\Brand;
use app\common\model\CarType;
use app\common\model\CarFile;
use app\common\model\CarAttribute;
use app\common\model\Cars as CarsModel;
use app\common\model\CarAttr;
use app\common\model\Company;
use app\common\model\Personal;
use app\common\request\ClientLai;
use app\common\request\Oss;
use app\common\controller\Execl;
use app\common\controller\Gps;
use app\common\model\CarsInfo;
use app\common\enums\ResultEnum;
use app\common\utils\ResultVOUtil;
use think\Log;



class Cars extends Base
{
    /**
     *车辆列表
     */
    public function index()
    {

        $request = Request::instance();
        
        if($request->isAjax()){
            $post = $request->post();
            if( !empty($post['datemin']) && !empty($post['datemax']) ){
                $where['create_time'] = ['between time',[$post['datemin'],$post['datemax']]];                  
                    
            }
            if ( empty($post['datemin']) && !empty($post['datemax']) ){             
                $where['create_time'] = ['<= time',$post['datemax']];
                    
                    
            }
            if ( !empty($post['datemin']) && empty($post['datemax']) ) {
                $where['create_time'] = ['> time',$post['datemin']];
                 
            }
            if ( !empty($post['search_inpute']) ) {
                $where['car_sn|car_unique_id|cardcode|equipment_id|sim_id'] = ['like','%'.$post['search_inpute'].'%'];
                    
            }
            if ( !empty($post['relevance']) ) {
                $where['relevance'] = $post['relevance'];     
                    
            }
            if ( !empty($post['car_usage']) ) {
                $where['car_usage'] = $post['car_usage'];     
                    
            }

            if ( !empty($post['agency_id']) ) {
                $where['agency_id'] = $post['agency_id'];
                    
            }
            if ( !empty($post['brand_id']) ) {
                $where['brand_id'] = $post['brand_id'];
                    
            }
            if ( !empty($post['supplier_no']) ) {
                $where['supplier_no'] = $post['supplier_no'];
                    
            }
            if ( !empty($post['sim_card']) ) {
                $where['sim_card'] = $post['sim_card'];
                    
            }

            if( empty($where) ){
                $where = '1=1';
            }       
            $model= CarsModel::with('brand,agency,carsInfo')
                            ->where($where)
                            ->order('car_id', 'desc')
                            ->field('car_id,car_sn, agency_id,car_unique_id,car_usage,relevance,brand_id,holder_type,holder_id,create_time,band_status,supplier_no,sim_card')
                            ->paginate($post['length'],false,[
                                    'type'     => 'bootstrap',
                                    'var_page' => 'page',
                                    'page'=>$post['start']/$post['length'] +1 ,
                                ]);
            if(count($model)>=1){
                foreach ($model as $key => $value) {
                    $value['agency_name'] = $value->agency['name'];
                    $value['brand_name'] = $value->brand['name'];
                    $res['data'][] = $value;
                }
                
                $res['recordsTotal'] = $res['recordsFiltered'] = $model->total();
            }else{
                $res['data'] = '';
                $res['recordsTotal'] = $res['recordsFiltered'] =0;
            }

           
            return $res;

        }else{
            
            $model = CarsModel::count();
            $brand = Brand::all();
            $agency = Agency::all();
            // unset($agency[0]);
            $car_usage = [
                1=>[
                    'name'=>'库存',
                    'children'=>[
                        1=>'待整备',
                        2=>'整备完成',
                        9=>'在修待修',
                        15=>'办理违章',
                        19=>'报废'
                    ]
                ],
                2=>[
                    'name'=>'分时租赁',
                    'children'=>[
                        1=>'待整备',
                        3=>'分时租赁',
                        9=>'在修待修',
                        10=>'体验用车',
                        13=>'展示用车',
                        15=>'办理违章',
                        16=>'出险',
                        17=>'紧急调用',
                        18=>'设备故障'
                    ]
                ],
                3=>[
                    'name'=>'长租',
                    'children'=>[
                        6=>'长租',
                        9=>'在修待修',
                        10=>'体验用车',
                        13=>'展示用车'
                    ]
                ],
                4=>[
                    'name'=>'以租代购',
                    'children'=>[
                        8=>'以租代购',
                        9=>'在修待修',
                    ]
                ],
                5=>[
                    'name'=>'企业用车',
                    'children'=>[
                        4=>'企业用车',
                        9=>'在修待修',
                        15=>'办理违章'
                    ]
                ],
                6=>[
                    'name'=>'共享用车',
                    'children'=>[
                        5=>'共享用车',
                        9=>'在修待修',
                    ]
                ],
                7=>[
                    'name'=>'公务用车',
                    'children'=>[
                        11=>'公务用车',
                        9=>'在修待修',
                        15=>'办理违章'
                    ]
                ],
                8=>[
                    'name'=>'自测用车',
                    'children'=>[
                        7=>'自测用车',
                        9=>'在修待修',
                    ]
                ],
                9=>[
                    'name'=>'销售',
                    'children'=>[
                        12=>'销售售出',
                        14=>'待售出'
                    ]
                ]
            ];
            $this->assign('car_usage',$car_usage);
            $this->assign('number',$model);
            $this->assign('brand',$brand);
            $this->assign('agency',$agency);
            return $this->fetch();
        }
    }

    /**
     * 车辆详情页
     */
    public function details($id=1)
    {
        
        $cars = CarsModel::get($id);
        if($cars['supplier_no'] == 1376920002){
            $config = config('gz_blt');
            $obj = new ClientLai($config['user_name'],$config['password']);
            $res = $obj->request_post(rtrim($config['url'],'/').'/api/vehicle/carData/getRtInfo',http_build_query(['car_unique_id'=>$cars['car_unique_id']]));
            $arr = json_decode($res,true);
            if($arr['result'] == 0){
                if(empty($arr['data'][0])){
                    $data = null;
                }else{
                    $cars_data = $arr['data'][0];
                    $cars_data['long_term_lease'] = $cars_data['supplier_rent_type'];
                    $data = $cars_data; 
                }
            }else{
                $data = null;
            }

        }elseif($cars['supplier_no'] == 1376920003){
            $config = config('local_iot');
            $obj = new ClientLai($config['user_name'],$config['password']);
            $res = $obj->request_post(rtrim($config['url'],'/').'/car/getRtInfo',http_build_query(['car_unique_id'=>$cars['car_unique_id']]));
            $arr = json_decode($res,true);
            if($arr['result'] == 0){
                if(empty($arr['data'][0])){
                    $data = null;  
                }else{
                    $data = $arr['data'][0];
                    
                }
            }else{
                $data = null;
            }

        }elseif($cars['supplier_no'] == 1376920001){
            $carInfo = CarsInfo::get($cars['car_unique_id']);
            if($carInfo){
                $data = $carInfo;
              
            }else {
                $data = null;
            }

        }else{
            $data = null;
        }
        if($data){
            $result = Gps::geocode($data['longitude'],$data['latitude']);
            if($result){
                $gaodeapi = json_decode($result,true);           
            }else{
                $gaodeapi = null;
            }  
        }else{
            $gaodeapi = null;
        }

        $this->assign('data',$data);
        $this->assign('cars',$cars);
        $this->assign('car_breed',['小型轿车','SUV','中巴','未知']);
        $this->assign('car_usage',['未知','库存','分时租赁','长租','以租代购','企业用车','共享用车','公务用车','自测用车','销售']);
        $this->assign('relevance',['未知','待整备','整备完成','分时租赁','企业用车','共享用车','长租','自测用车','以租代购','在修待修','体验用车','公务用车','销售售出','展示用车','待售出','办理违章','出险','紧急调用','设备故障']);

        $this->assign('car_park',['未知','香雪停车场','独秀苑停车场','双鱼汇停车场','金宏别克汽车园区停车场','静兰停车场']);
        $this->assign('gaodeapi',$gaodeapi);
        return $this->fetch();

    }

    /**
     * 车辆基础数据导入
     */
    public function excelToData()
    {
        $request = Request::instance();
        if($request->isPost()){
            $file = $request->file('excel');
            if($file){
                $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
                if($info){
                    // 成功上传后 获取上传信息
                    $url = $info->getSaveName();
                    $ext = $info->getExtension();
                    $path = ROOT_PATH . 'public' . DS . 'uploads/'.$url;
                    $excel = new Execl;
                    $excelData = $excel->readerBase($path);
                    
                    if(empty($excelData)){
                        $this->error('数据格式不合法');
                    }
                    $updateNum = 0;
                    $insertNum = 0;
                    // 遍历数据加入到数据库中去
                    
                    foreach ($excelData as $key => $value) {
                        if($key==0){
                            continue;
                        }
                        // 查看库中是否有数据
                        $car_id = Db::name('cars')->where(['car_unique_id' => $value[1]])->find();
                        $carsData['car_sn'] = $value[0]??'';
                        $carsData['car_unique_id'] = $value[1]??'';
                        $carsData['motor_id'] = (string)$value[2]??'';
                        $carsData['car_name'] = $value[3]??'';
                        $bandName['name'] = $value[4]??'';
                        $carsData['brand_id'] = Db::name('brand')->where($bandName)->value('id');

                        $carsData['car_usage'] = $value[6]??'';
                        switch ($carsData['car_usage']) {
                            case '库存':
                                
                                $carsData['car_usage'] = 1;
                                break;
                            case '分时租赁':
                                
                                $carsData['car_usage'] = 2;
                                break;
                            case '长租':
                                
                                $carsData['car_usage'] = 3;
                                break;
                            case '以租代购':
                                
                                $carsData['car_usage'] = 4;
                                break;
                            case '企业用车':
                                
                                $carsData['car_usage'] = 5;
                                break;
                            case '共享用车':
                                
                                $carsData['car_usage'] = 6;
                                break;
                            case '公务用车':
                                
                                $carsData['car_usage'] = 7;
                                break;
                            case '自测用车':
                                
                                $carsData['car_usage'] = 8;
                                break;
                            case '销售':
                                
                                $carsData['car_usage'] = 9;
                                break;
                            
                            default:
                                $carsData['car_usage'] = null;
                                break;
                        }


                        $carsData['relevance'] = $value[7]??'';
                        switch ($carsData['relevance']) {
                            case '待整备':
                                
                                $carsData['relevance'] = 1;
                                break;
                            case '整备完成':
                                
                                $carsData['relevance'] = 2;
                                break;
                            case '分时租赁':
                                
                                $carsData['relevance'] = 3;
                                break;
                            case '企业用车':
                                
                                $carsData['relevance'] = 4;
                                break;
                            case '共享用车':
                                
                                $carsData['relevance'] = 5;
                                break;
                            case '长租':
                                
                                $carsData['relevance'] = 6;
                                break;
                            case '自测用车':
                                
                                $carsData['relevance'] = 7;
                                break;
                            case '以租代购':
                                
                                $carsData['relevance'] = 8;
                                break;
                            case '在修待修':
                                
                                $carsData['relevance'] = 9;
                                break;
                            case '体验用车':
                                
                                $carsData['relevance'] = 10;
                                break;
                            case '公务用车':
                                
                                $carsData['relevance'] = 11;
                                break;
                            case '销售售出':
                                
                                $carsData['relevance'] = 12;
                                break;
                            case '展示用车':
                                
                                $carsData['relevance'] = 13;
                                break; 
                            case '待售出':
                                
                                $carsData['relevance'] = 14;
                                break; 
                            case '办理违章':
                                $carsData['relevance'] = 15;
                                break;
                            case '出险':
                                $carsData['relevance'] = 16;
                                break;
                            case '紧急调用':
                                $carsData['relevance'] = 17;
                                break;
                            case '设备故障':
                                $carsData['relevance'] = 18;
                                break;
                            case '报废':
                                $carsData['relevance'] = 19;
                                break;
                            default:
                                $carsData['relevance'] = null;
                                break;
                        }

                        $carsData['car_park'] = $value[10]??'';
                        switch ($carsData['car_park']) {
                            case '香雪停车场':
                                
                                $carsData['car_park'] = 1;
                                break;
                            case '独秀苑停车场':
                                
                                $carsData['car_park'] = 2;
                                break;
                            case '双鱼汇停车场':
                                
                                $carsData['car_park'] = 3;
                                break;  
                            case '金宏别克汽车园区停车场':
                                
                                $carsData['car_park'] = 4;
                                break;
                            case '静兰停车场':
                                
                                $carsData['car_park'] = 5;
                                break;  
                            default:
                                $carsData['car_park'] = null;
                                break;
                        }
                        $agencyName['name'] = (string)$value[9]??'';
                        $carsData['agency_id'] =  Db::name('agency')->where($agencyName)->value('id');

                        $newArr = array_filter($carsData);

                        switch ($value[5]??'') {
                            case '小轿车':
                                
                                $newArr['car_breed'] = 0;
                                break;
                            case 'SUV':
                                
                                $newArr['car_breed'] = 1;
                                break;
                            case '中巴':
                                
                                $newArr['car_breed'] = 2;
                                break;  
                            default:
                                $newArr['car_breed'] = null;
                                break;
                        }
                        $companyName['name'] = $value[8]??'';
                        $company = Db::name('company')->where($companyName)->value('id');
                        if($company){
                            $newArr['holder_type'] = 0;
                            $newArr['holder_id'] = $company;
                        }
                        if($car_id && !empty($newArr['car_unique_id'])){
                            $newArr['update_time'] = time();
                            $res = Db::name('cars')->where('car_id',$car_id['car_id'])->update($newArr);
                            $updateNum++;
                        }elseif(!empty($newArr['car_unique_id'])){
                            $newArr['create_time'] = time();
                            $newArr['update_time'] = time();
                            $res = Db::name('cars')->insert($newArr);
                            $insertNum++;                   
                        }
                    }

                    $resArr = ['status'=>0,'msg' =>'更新'.$updateNum.'条,插入'.$insertNum.'条'];
                    return $resArr;
                }else{
                    $this->error($file->getError());
                }
            }else{
                $this->error('没有上传文件');
            }
        }else{
            return $this->fetch('excel_to_data');
        }
    }

    /**
     * 车辆基础数据模板
     */
    public function carExcel()
    {
        
        $brand = Brand::all();
        $company = Company::all();
        $agency = Agency::all();
        $excel = new Execl;
        $excel->carExcel($brand,$company,$agency);
                    

    }


    /**
     * 绑定车辆
     */
    public function bandCars($id)
    {
           
        $model = CarsModel::get($id);

        if($model['supplier_no'] == 1376920002){
            $config = config('blt_lai');
            $obj = new ClientLai($config['user_name'],$config['password']);
            $data['supplier_no'] = $model['supplier_no'];
            $data['car_unique_id'] = $model['car_unique_id'];
            $data['equipment_id'] = $model['equipment_id'];
            $data['bluetooth_id'] = ltrim($model['equipment_id'],0);
            $data['license_plate'] = $model['car_sn'];
            
            $res = $obj->request_post(rtrim($config['url'],'/').'/bind_car',$data);

            $arr = json_decode($res,true);


            if($arr['result']==0){          
                try{
                    $model->band_status = 1;
                    $model->save();

                }catch(\Exception $e){
                    Log::record('【更新数据库车辆绑定状态】:'.$e->getMessage(),'error');
                    return ResultVOUtil::error(ResultEnum::UPDATE_ERROR);
                }

            }
            return $arr;
            
        }elseif($model['supplier_no'] == 1376920003){
            $config = config('local_iot');
            $obj = new ClientLai($config['user_name'],$config['password']);
            $data['supplierNo'] = 1376920002;
            $data['carUniqueId'] = $model['car_unique_id'];
            $data['machineNum'] = $model['equipment_id'];
            $data['deviceName'] = $model['equipment_id'];
            $data['licensePlate'] = $model['car_sn'];
            $res = $obj->request_post(rtrim($config['url'],'/').'/car/bindCar',$data);
            $arr = json_decode($res,true);

            if($arr['result']==0){          
                try{
                    $model->band_status = 1;
                    $model->save();
                    
                }catch(\Exception $e){
                    Log::record('【更新数据库车辆绑定状态】:'.$e->getMessage(),'error');
                    return ResultVOUtil::error(ResultEnum::UPDATE_ERROR);
                }

            }
            return $arr;
        }
        
    }

    /**
     * 解绑车辆
     */
    public function unBandCars($id)
    {

        $model = CarsModel::get($id);

        if($model['supplier_no'] == 1376920002){

            $config = config('blt_lai');
            $obj = new ClientLai($config['user_name'],$config['password']);

            $data['supplierNo'] = $model['supplier_no'];
            $data['carUniqueId'] = $model['car_unique_id'];
            
            $res = $obj->request_post(rtrim($config['url'],'/').'/unbind_car',$data);

            $arr = json_decode($res,true);


            if($arr['result']==0){          
                try{
                    $model->band_status = 0;
                    $model->save();
                    
                }catch(\Exception $e){
                    Log::record('【更新数据库车辆解绑状态】:'.$e->getMessage(),'error');
                    return ResultVOUtil::error(ResultEnum::UPDATE_ERROR);
                }

            }

            return $arr;

        }elseif($model['supplier_no'] == 1376920003){

            $config = config('local_iot');
            $obj = new ClientLai($config['user_name'],$config['password']);
            $data['supplierNo'] = 1376920002;
            $data['carUniqueId'] = $model['car_unique_id'];
            $res = $obj->request_post(rtrim($config['url'],'/').'/car/unbindCar',$data);

            $arr = json_decode($res,true);

            if($arr['result']==0){          
                try{
                    $model->band_status = 0;
                    $model->save();
                    
                }catch(\Exception $e){
                    Log::record('【更新数据库车辆解绑状态】:'.$e->getMessage(),'error');
                    return ResultVOUtil::error(ResultEnum::UPDATE_ERROR);
                }

            }

            return $arr;
        }
    }

    /**
     * 删除车辆图片
     */
    public function carsImgDel($id)
    {
        $url = CarFile::get($id);
        $oss = new Oss();
        $res = false;
        if($oss->unlinkOss($url['file_url'])){
            $res = CarFile::destroy($id);
            
        }
        if(!$res) {
            return ResultVOUtil::error(ResultEnum::DEL_ERROR);
        }
        return ResultVOUtil::success('');
    }

    /**
     * 删除车辆
     */
    public function delete($id)
    {
        $data = CarsModel::get($id);
        if($data['band_status'] == 1){
            return ResultVOUtil::error(ResultEnum::DEL_ERROR['code'], '删除失败,请解除绑定');
        }
        $res = CarsModel::destroy($id);
        if(!$res) {
            return ResultVOUtil::error(ResultEnum::DEL_ERROR['code'], '删除失败,请稍后再试');

        }
        return ResultVOUtil::success('');
    }

    /**
     * 编辑车辆
     */
    public function edit($car_id=1)
    {
        $request = Request::instance();

        if($request->isPost()){
            
            // dump($_POST);

            $data = $request->post();
            $car_id = $data['car_id'];
            // 商品基础信息添加
            $model = new CarsModel();

            $car_unique_id = $model->where(['car_id'=>$car_id])->value('car_unique_id');
            
            $result = $model->allowField(true)->validate(true)->save($data,['car_id' => $data['car_id']]);
            
            if(false === $result){
                // 验证失败 输出错误信息
                $this->error($model->getError());
            }



            CarsInfo::destroy($car_unique_id);
            // dump($car_unique_id);
            $cars_info = new CarsInfo;
            
            $cars_info->save(['supplier_no' => $data['supplier_no'],'car_unique_id'=>$data['car_unique_id']]);
            
               

            //电子文件
            $travel_image = $request->file('travel_image');
            $register_image = $request->file('register_image');
            $image = $request->file('image');
            if($travel_image || $register_image || $image){
                $oss = new Oss();
            }
            //添加行驶证
            if($travel_image){
                foreach ($travel_image as $key => $value) {
                    $url = $oss->uploadOss($value);
                    
                    if($url){
                        Db::name('car_file')->insert(['car_id'=>$car_id,'file_url'=>$url,'file_type'=>0]);
                    }
                }
            }

            //添加登记证
            if($register_image){
                foreach ($register_image as $key => $value) {
                    $url = $oss->uploadOss($value);
                    
                    if($url){
                        Db::name('car_file')->insert(['car_id'=>$car_id,'file_url'=>$url,'file_type'=>1]);
                    }
                }
            }
            //其它电子文件的添加 joy_car_images car_id,image_url,image_type=2
            if($image){
                foreach ($image as $key => $value) {
                    $url = $oss->uploadOss($value);
                    
                    if($url){
                        Db::name('car_file')->insert(['car_id'=>$car_id,'file_url'=>$url,'file_type'=>2]);
                    }
                }
            }

            //车辆属性的添加 joy_car_attr car_id,attr_id,attr_value
            if(!empty($data['car_attr'])){
                
                $attrModel = new CarAttr();
                $carAttrArr = $data['car_attr'];


                foreach ($carAttrArr as $key => $value) {
                    $attrData[] = ['car_id'=>$car_id,'attr_id'=>$key,'attr_value'=>$value];         
                }
                // 删除原来的数据
                        
                CarAttr::destroy(['car_id' => $car_id]);
                $result = $attrModel->saveAll($attrData);

            }

            if($result){
                $this->success('更新成功', 'index/Cars/index');
            } else {
                $this->error('更新失败');
            }
            
        }else{
            $brand = Brand::all();
            $type = Db::table('joy_car_type')->column('id,name');
            $data = CarsModel::get($car_id);
            
            //所有人
            $data['holder_id'] = $data->getData('holder_id');
            if($data['holder_type']==0){
                $holder = Db::table('joy_company')->column('id,name');
            }else{
                $holder = Db::table('joy_personal')->column('id,name');

            }

            // 图片
            $images = Db::name('car_file')->where(['car_id'=>$car_id])->order('file_type')->column('id,file_url,file_type');
            
            //车辆属性
            $carAttribute = CarAttribute::all(['type_id'=>$data['car_type']]);
            foreach ($carAttribute as $key => $value) {
                $attr_value = Db::name('car_attr')
                                ->where(['car_id'=>$car_id,'attr_id'=>$value['attr_id']])
                                ->column('attr_value');
                $carAttribute[$key]['attr_value'] = $attr_value[0];
                
            }
            //经销商
            $agency = Agency::all();
            unset($agency[0]);
            $car_usage = [
                1=>[
                    'name'=>'库存',
                    'children'=>[
                        1=>'待整备',
                        2=>'整备完成',
                        9=>'在修待修',
                        15=>'办理违章',
                        19=>'报废'
                    ]
                ],
                2=>[
                    'name'=>'分时租赁',
                    'children'=>[
                        1=>'待整备',
                        3=>'分时租赁',
                        9=>'在修待修',
                        10=>'体验用车',
                        13=>'展示用车',
                        15=>'办理违章',
                        16=>'出险',
                        17=>'紧急调用',
                        18=>'设备故障'
                    ]
                ],
                3=>[
                    'name'=>'长租',
                    'children'=>[
                        6=>'长租',
                        9=>'在修待修',
                        10=>'体验用车',
                        13=>'展示用车'
                    ]
                ],
                4=>[
                    'name'=>'以租代购',
                    'children'=>[
                        8=>'以租代购',
                        9=>'在修待修',
                    ]
                ],
                5=>[
                    'name'=>'企业用车',
                    'children'=>[
                        4=>'企业用车',
                        9=>'在修待修',
                        15=>'办理违章'
                    ]
                ],
                6=>[
                    'name'=>'共享用车',
                    'children'=>[
                        5=>'共享用车',
                        9=>'在修待修',
                    ]
                ],
                7=>[
                    'name'=>'公务用车',
                    'children'=>[
                        11=>'公务用车',
                        9=>'在修待修',
                        15=>'办理违章'
                    ]
                ],
                8=>[
                    'name'=>'自测用车',
                    'children'=>[
                        7=>'自测用车',
                        9=>'在修待修',
                    ]
                ],
                9=>[
                    'name'=>'销售',
                    'children'=>[
                        12=>'销售售出',
                        14=>'待售出'
                    ]
                ]
            ];
            $this->assign('car_usage',$car_usage);
            $this->assign('brand',$brand);
            $this->assign('holder',$holder);
            $this->assign('type',$type);
            $this->assign('data',$data);
            $this->assign('images',$images);
            $this->assign('carAttribute',$carAttribute);
            $this->assign('agency_id',$agency);

            return $this->fetch();

        }
    }

    /**
     *添加车辆
     */
    public function add()
    {
        $request = Request::instance();

        if($request->isPost()){

            $data = $request->post();
            //基础信息添加
            $model = new CarsModel();
            
            $result = $model->validate(true)->allowField(true)->save($data);
            if(false === $result){
                // 验证失败 输出错误信息
                $this->error($model->getError());
            }

            $car_id = $model->car_id;

            //电子文件
            $travel_image = $request->file('travel_image');
            $register_image = $request->file('register_image');
            $image = $request->file('image');
            if($travel_image || $register_image || $image){
                $oss = new Oss();
            }
            //添加行驶证
            if($travel_image){
                foreach ($travel_image as $key => $value) {
                    $url = $oss->uploadOss($value);
                    
                    if($url){
                        Db::name('car_file')->insert(['car_id'=>$car_id,'file_url'=>$url,'file_type'=>0]);
                    }
                }
            }

            //添加登记证
            if($register_image){
                foreach ($register_image as $key => $value) {
                    $url = $oss->uploadOss($value);
                    
                    if($url){
                        Db::name('car_file')->insert(['car_id'=>$car_id,'file_url'=>$url,'file_type'=>1]);
                    }
                }
            }
            //其它电子文件的添加 joy_car_images car_id,image_url,image_type=2
            if($image){
                foreach ($image as $key => $value) {
                    $url = $oss->uploadOss($value);
                    
                    if($url){
                        Db::name('car_file')->insert(['car_id'=>$car_id,'file_url'=>$url,'file_type'=>2]);
                    }
                }
            }

            //车辆属性的添加 joy_car_attr car_id,attr_id,attr_value
            if(!empty($data['car_attr'])){
                $attrModel = new CarAttr();
                $carAttrArr = $data['car_attr'];

                foreach ($carAttrArr as $key => $value) {
                    if(!empty($value)){
                        $attrData[] = ['car_id'=>$car_id,'attr_id'=>$key,'attr_value'=>$value];         
                    }
                }           
                $result = $attrModel->saveAll($attrData);

            }

            if($result){
                $this->success('新增成功', 'Cars/index');
            } else {
                $this->error('新增失败');
            }

        }else{
            $brand = Brand::All();
            $holder = Company::scope('status')->column('id,name');
            $type = Db::table('joy_car_type')->column('id,name');
            $agency = Agency::column('id,name');
            unset($agency[1]);
        
            $car_usage = [
                1=>[
                    'name'=>'库存',
                    'children'=>[
                        1=>'待整备',
                        2=>'整备完成',
                        9=>'在修待修',
                        15=>'办理违章',
                        19=>'报废'
                    ]
                ],
                2=>[
                    'name'=>'分时租赁',
                    'children'=>[
                        3=>'分时租赁',
                        9=>'在修待修',
                        10=>'体验用车',
                        13=>'展示用车',
                        15=>'办理违章',
                        16=>'出险',
                        17=>'紧急调用',
                        18=>'设备故障',
                        1=>'待整备'
                    ]
                ],
                3=>[
                    'name'=>'长租',
                    'children'=>[
                        6=>'长租',
                        9=>'在修待修',
                        10=>'体验用车',
                        13=>'展示用车'
                    ]
                ],
                4=>[
                    'name'=>'以租代购',
                    'children'=>[
                        8=>'以租代购',
                        9=>'在修待修',
                    ]
                ],
                5=>[
                    'name'=>'企业用车',
                    'children'=>[
                        4=>'企业用车',
                        9=>'在修待修',
                        15=>'办理违章'
                    ]
                ],
                6=>[
                    'name'=>'共享用车',
                    'children'=>[
                        5=>'共享用车',
                        9=>'在修待修',
                    ]
                ],
                7=>[
                    'name'=>'公务用车',
                    'children'=>[
                        11=>'公务用车',
                        9=>'在修待修',
                        15=>'办理违章'
                    ]
                ],
                8=>[
                    'name'=>'自测用车',
                    'children'=>[
                        7=>'自测用车',
                        9=>'在修待修',
                    ]
                ],
                9=>[
                    'name'=>'销售',
                    'children'=>[
                        12=>'销售售出',
                        14=>'待售出'
                    ]
                ]
            ];
              
            $this->assign('brand',$brand);
            $this->assign('holder',$holder);
            $this->assign('type',$type);
            $this->assign('agency',$agency);
            $this->assign('car_usage',$car_usage);
            return $this->fetch();

        }
    }
    
    /**
     * 模型列表
     */
    public function typeList()
    {
        $carsTypeList = CarType::all();                
        // $carsTypeList = $model->order("id desc")->paginate(10);

        $this->assign('carsTypeList',$carsTypeList);
        return $this->fetch('type_list');

    }

    /**
     * 删除模型
     */
    public function typeDel($id)
    {
        //需要删除模型下所有属性
        
        $res = CarType::destroy($id);
        if(!$res) {
            return ResultVOUtil::error(ResultEnum::DEL_ERROR);
        }
        
        if(CarAttribute::get(['type_id'=>$id])){
            $res = CarAttribute::destroy(['type_id'=>$id]);
            if(!$res) {
                return ResultVOUtil::error(ResultEnum::DEL_ERROR);
            }
            
        }
        return ResultVOUtil::success('');

    }

    /**
     * 添加模型
     */
    public function typeAdd()
    {
        $request = Request::instance();


        if($request->isAjax())
        {
            // $msg['status'] = 1;
            //      $msg['msg'] = 2;
                    
            //      return json($msg);die;
            $data = $request->post();

            $model = new CarType();

            $model->data($data);
            $res = $model->allowField(true)->save();

            if($res){

                return ResultVOUtil::success('');
                
            }else{

                return ResultVOUtil::error(ResultEnum::WRITE_ERROR);
            }
                    
        }else{

            return $this->fetch('type_add');        
        }
    }

    /**
     * 模型编辑
     */
    public function typeEdit()
    {
        $request = Request::instance();


        if($request->isAjax())
        {
            $data = $request->post();

            $model = new CarType();

            
            $res = $model->update($data);

            if($res){
                return ResultVOUtil::success('');
                
            }else{
                return ResultVOUtil::error(ResultEnum::UPDATE_ERROR);
            }

        }else{

            $id = $request->get('id');  
            $data = Db::table('joy_car_type')->where(['id'=>$id])->find();
            
            $this->assign('data',$data);

            return $this->fetch('type_edit');
        }

    }

    /**
     * 属性列表
     */
    public function attrList()
    {
        $model = new CarAttribute();
        $data = $model->select();

        $this->assign('writer',['手工录入','多行文本','列表选择']);
        $this->assign('data',$data);
        return $this->fetch('attr_list');
    }

    /**
     * 删除属性
     */
    public function attrDel($id)
    {
        
        $res = CarAttribute::destroy($id);
        if(!$res) {
           return ResultVOUtil::error(ResultEnum::DEL_ERROR);
        }
        
        return ResultVOUtil::success('');
    }

    /**
     * 编辑属性
     */
    public function attrEdit($attr_id)
    {
        $request = Request::instance();


        if($request->isAjax())
        {
            $msg['status'] = 0;
            $data = $request->post();

            $model = new CarAttribute();

            
            $res = $model->update($data);

            if($res){
                return ResultVOUtil::success('');
                
            }else{
                return ResultVOUtil::error(ResultEnum::UPDATE_ERROR);
            }
                    
        }else{

            
            $data = Db::name('car_attribute')->where(['attr_id'=>$attr_id])->find();
            // 查询模型
            $type = Db::table('joy_car_type')->column('id,name');
            // dump($type);
            $this->assign('type',$type);

            $this->assign('data',$data);

            return $this->fetch('attr_edit');
        }
    }

    /**
     * 添加属性
     */
    public function attrAdd()
    {
        $request = Request::instance();

        if($request->isAjax())
        {
            
            $data = $request->post();
            $data['attr_values'] = trim($data['attr_values']);
            $model = new CarAttribute;
            $model->data($data);

            $res = $model->allowField(true)->save();

            if($res){
                return ResultVOUtil::success('');
                
            }else{
                return ResultVOUtil::error(ResultEnum::WRITE_ERROR);
            }
               
        }
        else
        {
            // 查询模型
            $type = Db::table('joy_car_type')->column('id,name');
            // dump($type);
            $this->assign('type',$type);

            return $this->fetch('attr_add');
            
        }
    }

    /**
     * ajax获取共享车主
     */
    public function ajaxGetHolder($type)
    {
        if($type == 1){
            return Personal::column('id,name');
        }elseif($type ==="0"){
            return Company::scope('status')->column('id,name');

        }else{
            return ['请选择'];
        }

    }

    /**
     * ajax获取模板属性
     */
    public function ajaxGetType($type = 1)
    {

        $data = CarAttribute::all(['type_id'=>$type]);
        // $data = $model->toArray(); // 

        return $data;

    }

    /*历史数据*/
    public function previous($car_unique_id=1,$time_start=0,$time_end=0,$supplier_no=1){

        if($time_start ==0 || $time_end ==0){
            $data['time_start'] = time()-3600;
            $data['time_end'] = time();
        }else{
            $data['time_start'] = strtotime($time_start);
            $data['time_end'] = strtotime($time_end);
        }

        $data['car_unique_id'] = $car_unique_id;

        if($supplier_no == 1376920003){

            $config = config('local_iot');
            $obj = new ClientLai($config['user_name'],$config['password']);
            $res = $obj->request_post(rtrim($config['url'],'/').'/car/getHisInfo',$data);
            $arr = json_decode($res,true);

            if($arr['result'] == 0){
                if(!empty($arr['data'])){
                    
                    $cars = $arr['data'];

                }else{
                    $cars = [];
                }
                
            }else{
                $cars = [];
            }

        }elseif($supplier_no == 1376920002){

            $config = config('gz_blt');
            $obj = new ClientLai($config['user_name'],$config['password']);
            $res = $obj->request_post(rtrim($config['url'],'/').'/api/vehicle/carData/getHisInfo',http_build_query($data));
            $arr = json_decode($res,true);

            if($arr['result'] == 0){
                if(!empty($arr['data'])){
                    $cars = $arr['data'];
                    foreach ($cars as $key => &$value) {
                       $value['long_term_lease'] = $value['supplier_rent_type'];
                    }
                    
                }else{
                    $cars = [];
                }
                
            }else{

                $cars = [];
            }

        }else{
            $cars = [];
        }
  
        $this->assign('time_start',$data['time_start']);
        $this->assign('time_end',$data['time_end']);
        $this->assign('car_unique_id',$car_unique_id);
        $this->assign('supplier_no',$supplier_no);
        $this->assign('data',$cars);
        return $this->fetch();
        
    }

    
}